import {useLocation} from "react-router-dom";
import {useEffect, useState} from "react";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import useMessage from "antd/es/message/useMessage";
import TraceLogSearch from "../../../components/console/traceLog/traceLogSearch";
import {Card, Tag} from "antd";
import {ClockCircleOutlined, ClusterOutlined, CodeOutlined, PlayCircleOutlined, StopOutlined} from "@ant-design/icons";

/**
 * 链路追踪日志页面
 */
const ConsoleTraceLogPage = () => {

    const [messageApi, contextHolder] = useMessage();
    const location = useLocation();
    const searchParams = new URLSearchParams(location.search);

    // 从URL获取traceId
    const [traceId, setTraceId] = useState(searchParams.get("traceId"));
    // 链路追踪日志查询结果
    const [traceLogs, setTraceLogs] = useState([]);

    /**
     * 根据链路追踪id查询请求日志
     */
    const searchTraceLogsByTraceId = (traceId) => {
        if (!traceId) {
            setTraceLogs([]);
            return;
        }
        RequestUtils.post(RequestApis.systemLog.pageTraceLog, {
            traceId: traceId
        }).then(res => {
            setTraceLogs(res.data.data || []);
        }).catch(err => messageApi.error(err.message))
    }

    /**
     * 页面打开时自动查询链路追踪日志
     */
    useEffect(() => {
        searchTraceLogsByTraceId(traceId);
        // eslint-disable-next-line
    }, []);

    /**
     * 解析日志内容，提取关键信息
     */
    const parseLogContent = (logContent) => {
        const regex = /\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{3})] \[(.*?)] \[(.*?)] \{([^:]+):(\d+)} - ([\s\S]*)/;
        const match = logContent.match(regex);

        if (match) {
            return {
                time: match[1],
                thread: match[2],
                level: match[3],
                className: match[4],
                lineNumber: match[5],
                content: match[6].replace(/\r\n/g, '\n')
            };
        }
        return {
            time: '',
            thread: '',
            level: 'INFO',
            className: '',
            lineNumber: '',
            content: logContent.replace(/\r\n/g, '\n')
        };
    };

    /**
     * 获取日志级别对应的样式
     */
    const getLevelStyle = (level) => {
        switch (level.toUpperCase()) {
            case 'ERROR':
                return {
                    color: '#dc2626',
                    backgroundColor: 'rgba(220, 38, 38, 0.08)',
                    borderColor: 'rgba(220, 38, 38, 0.2)',
                    dotColor: '#dc2626'
                };
            case 'WARN':
                return {
                    color: '#ea580c',
                    backgroundColor: 'rgba(234, 88, 12, 0.08)',
                    borderColor: 'rgba(234, 88, 12, 0.2)',
                    dotColor: '#ea580c'
                };
            case 'INFO':
                return {
                    color: '#1e40af',
                    backgroundColor: 'rgba(30, 64, 175, 0.08)',
                    borderColor: 'rgba(30, 64, 175, 0.2)',
                    dotColor: '#1e40af'
                };
            case 'DEBUG':
                return {
                    color: '#7c3aed',
                    backgroundColor: 'rgba(124, 58, 237, 0.08)',
                    borderColor: 'rgba(124, 58, 237, 0.2)',
                    dotColor: '#7c3aed'
                };
            default:
                return {
                    color: '#059669',
                    backgroundColor: 'rgba(5, 150, 105, 0.08)',
                    borderColor: 'rgba(5, 150, 105, 0.2)',
                    dotColor: '#059669'
                };
        }
    };

    /**
     * 获取行背景色（移除白色，全部使用有色背景）
     */
    const getRowBgColor = (index) => {
        const colors = [
            'rgba(240, 247, 255, 0.9)',  // 淡蓝色背景
            'rgba(247, 250, 245, 0.9)',  // 淡绿色背景
            'rgba(255, 248, 245, 0.9)',  // 淡橙色背景
            'rgba(250, 245, 255, 0.9)'   // 淡紫色背景
        ];
        return colors[index % colors.length];
    };

    return (
        <div style={{
            padding: '16px',
            height: '100%'
        }}>
            {contextHolder}

            {/* 查询区域 */}
            <TraceLogSearch
                traceId={traceId}
                setTraceId={setTraceId}
                searchTraceLogsByTraceId={searchTraceLogsByTraceId}
            />

            {/* 日志展示区域 */}
            {traceLogs.length > 0 ? (
                <Card
                    style={{
                        boxShadow: '0 3px 16px rgba(0, 0, 0, 0.07)',
                        borderRadius: '8px',
                        border: '1px solid #f0f0f0',
                        marginTop: '24px',
                        backgroundColor: '#fff'
                    }}
                    bodyStyle={{
                        padding: '0',
                        overflow: 'hidden'
                    }}
                >
                    <div style={{padding: '20px'}}>
                        <div style={{
                            fontSize: '14px',
                            color: '#374151',
                            marginBottom: '16px',
                            display: 'flex',
                            alignItems: 'center',
                            gap: '8px',
                            fontWeight: 500
                        }}>
                            <ClockCircleOutlined style={{color: '#1e40af'}}/>
                            <span>共 {traceLogs.length} 条日志记录</span>
                        </div>

                        {/* 时间线日志列表 */}
                        <div style={{position: 'relative'}}>
                            {/* 时间线中轴线 */}
                            {traceLogs.length > 0 && (
                                <div style={{
                                    position: 'absolute',
                                    left: '28px',
                                    top: '0',
                                    bottom: '0',
                                    width: '2px',
                                    backgroundColor: getLevelStyle(traceLogs[0].logContent.match(/\[INFO]|\[ERROR]|\[WARN]|\[DEBUG]/)?.[0] || 'INFO').dotColor,
                                    opacity: 0.2
                                }}/>
                            )}

                            {traceLogs.map((item, index) => {
                                const logInfo = parseLogContent(item.logContent);
                                const isFirst = index === 0;
                                const isLast = index === traceLogs.length - 1;
                                const levelStyle = getLevelStyle(logInfo.level);
                                const rowBgColor = getRowBgColor(index);

                                return (
                                    <div
                                        key={index}
                                        style={{
                                            display: 'flex',
                                            padding: '16px 0',
                                            position: 'relative',
                                            backgroundColor: rowBgColor,
                                            transition: 'background-color 0.2s ease, transform 0.2s ease',
                                            paddingLeft: '64px',
                                            paddingRight: '20px',
                                            // 增强分割线：使用稍深颜色+轻微缩进
                                            borderBottom: index !== traceLogs.length - 1
                                                ? '1px solid #e2e8f0'
                                                : 'none',
                                            marginBottom: index !== traceLogs.length - 1 ? '1px' : 0
                                        }}
                                        onMouseEnter={(e) => {
                                            e.currentTarget.style.backgroundColor = `rgba(${levelStyle.dotColor.replace('#', '')}, 0.12)`;
                                            e.currentTarget.style.transform = 'translateX(2px)';
                                        }}
                                        onMouseLeave={(e) => {
                                            e.currentTarget.style.backgroundColor = rowBgColor;
                                            e.currentTarget.style.transform = 'translateX(0)';
                                        }}
                                    >
                                        {/* 时间线节点 */}
                                        <div style={{
                                            position: 'absolute',
                                            left: '20px',
                                            width: '24px',
                                            height: '24px',
                                            borderRadius: '50%',
                                            backgroundColor: levelStyle.dotColor,
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            zIndex: 1,
                                            boxShadow: `0 2px 4px rgba(${levelStyle.dotColor.replace('#', '')}, 0.2)`
                                        }}>
                                            {isFirst ? (
                                                <PlayCircleOutlined style={{color: '#fff', fontSize: '13px'}}/>
                                            ) : isLast ? (
                                                <StopOutlined style={{color: '#fff', fontSize: '13px'}}/>
                                            ) : (
                                                <div style={{
                                                    width: '10px',
                                                    height: '10px',
                                                    borderRadius: '50%',
                                                    backgroundColor: '#fff'
                                                }}/>
                                            )}
                                        </div>

                                        {/* 日志内容区域 */}
                                        <div style={{flex: 1}}>
                                            {/* 日志头部信息 */}
                                            <div style={{
                                                display: 'flex',
                                                flexWrap: 'wrap',
                                                gap: '16px',
                                                marginBottom: '10px'
                                            }}>
                                                <span style={{
                                                    fontSize: '13px',
                                                    color: '#1e3a8a',
                                                    display: 'flex',
                                                    alignItems: 'center',
                                                    gap: '6px',
                                                    fontWeight: 500
                                                }}>
                                                    <ClockCircleOutlined style={{fontSize: '13px', color: levelStyle.dotColor}}/>
                                                    <span>执行时间：{logInfo.time}</span>
                                                </span>

                                                <Tag
                                                    style={{
                                                        ...levelStyle,
                                                        fontSize: '12px',
                                                        padding: '3px 10px',
                                                        borderRadius: '14px',
                                                        border: `1px solid ${levelStyle.borderColor}`,
                                                        fontWeight: 500
                                                    }}
                                                >
                                                    {logInfo.level}
                                                </Tag>

                                                <span style={{
                                                    fontSize: '12px',
                                                    color: '#4b5563',
                                                    fontFamily: 'SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace',
                                                    backgroundColor: '#f8fafc',
                                                    padding: '3px 8px',
                                                    borderRadius: '4px',
                                                    border: '1px solid #e2e8f0'
                                                }}>
                                                    {logInfo.className}:{logInfo.lineNumber}
                                                </span>

                                                <span style={{
                                                    fontSize: '13px',
                                                    color: '#4b5563',
                                                    display: 'flex',
                                                    alignItems: 'center',
                                                    gap: '4px'
                                                }}>
                                                    <span style={{fontWeight: 500, color: '#6b7280'}}>线程：</span>
                                                    <span>{logInfo.thread}</span>
                                                </span>
                                            </div>

                                            {/* 日志内容 */}
                                            <div style={{
                                                fontSize: '13px',
                                                color: '#1f2937',
                                                lineHeight: 1.7,
                                                whiteSpace: 'pre-wrap',
                                                wordBreak: 'break-all',
                                                padding: '12px 16px',
                                                backgroundColor: 'rgba(255, 255, 255, 0.85)',  // 内容区半透明白色，与行背景区分
                                                borderRadius: '6px',
                                                borderLeft: `3px solid ${levelStyle.dotColor}`,
                                                border: `1px solid ${levelStyle.borderColor}`,
                                                fontFamily: logInfo.content.includes('sql语句')
                                                    ? 'SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace'
                                                    : 'system-ui, -apple-system, sans-serif',
                                                boxShadow: `0 1px 3px rgba(${levelStyle.dotColor.replace('#', '')}, 0.08)`
                                            }}>
                                                {logInfo.content.includes('=====================')
                                                    ? logInfo.content.replace(/\n/g, '\n  ')
                                                    : logInfo.content}
                                            </div>
                                        </div>

                                        {/* 服务名标签 */}
                                        <div style={{
                                            minWidth: '120px',
                                            marginLeft: '20px',
                                            display: 'flex',
                                            justifyContent: 'flex-end',
                                            alignItems: 'flex-start'
                                        }}>
                                            <div style={{
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '6px',
                                                backgroundColor: index % 2 === 0
                                                    ? 'rgba(59, 130, 246, 0.15)'
                                                    : 'rgba(16, 185, 129, 0.15)',
                                                border: index % 2 === 0
                                                    ? '1px solid rgba(59, 130, 246, 0.25)'
                                                    : '1px solid rgba(16, 185, 129, 0.25)',
                                                color: index % 2 === 0 ? '#1d4ed8' : '#059669',
                                                padding: '5px 12px',
                                                borderRadius: '6px',
                                                fontSize: '12px',
                                                fontWeight: 500,
                                                boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)'
                                            }}>
                                                <ClusterOutlined style={{fontSize: '13px'}}/>
                                                <span>{item.serviceName}</span>
                                            </div>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                </Card>
            ) : (
                <Card
                    style={{
                        textAlign: 'center',
                        padding: '60px 0',
                        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',
                        border: '1px solid #f0f0f0',
                        backgroundColor: '#fff',
                        marginTop: '24px',
                        height: 'calc(100% - 100px)'
                    }}
                >
                    <div style={{
                        color: '#6b7280',
                        fontSize: '14px',
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        gap: '16px'
                    }}>
                        <CodeOutlined style={{fontSize: '31px', color: '#94a3b8'}}/>
                        <span>暂无链路追踪日志数据</span>
                    </div>
                </Card>
            )}
        </div>
    )
}

export default ConsoleTraceLogPage;